import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import jsCookie from 'js-cookie'

const isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Index',
    component: () => import('../views/index/index.vue')
  },
  {
    path: '/m',
    name: 'MIndex',
    component: () => import('../mobile/index/index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/ml',
    name: 'MLogin',
    component: () => import('../mobile/login/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪一个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next('/login') 跳转
  const userId = jsCookie.get("userId");
  const info = localStorage.getItem('info')
  if ((to.path === "/login" || to.path === "/ml") && userId && info) {
    if (isMobile) {
      return next('/m');
    } else {
      return next('/');
    }
  }
  //解决页面刷新store会重置问题
  if (userId && info) {
    if (isMobile && to.path === '/') {
      return next('/m');
    } else if (!isMobile && to.path === '/m') {
      return next('/');
    }
    return next();
  } else {
    if(to.path !== "/login" && to.path !== "/ml"){
      if (isMobile ) {
        return next('/ml');
      } else {
        return next('/login');
      }
    }
    if (isMobile && to.path === '/login') {
      return next('/ml');
    } else if (!isMobile && to.path === '/ml') {
      return next('/login');
    }
    return next();
  }

});
export default router
